package com.lohika.builder
{
	import com.lohika.Constant;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	import flash.utils.getDefinitionByName;
	import flash.utils.getQualifiedClassName;

	public class CrystalBuilder extends AbstractCrystalBuilder
	{
		private static var offset:uint = 6;
		private static var fakeSprite:Sprite = new Sprite();
		
		
		override public function create(column:uint, row:uint, type:uint):void
		{
			entity.column = column;
			entity.row = row;
			entity.type = type;
		}

		override public function attachGraphics():void
		{
			const artClasses:Array = ["Red", "Blue",  "Green", "Violet", "Yellow", "Orange","Grey"  ]
			var className:String = 	artClasses[entity.type - 1];
			
			var ClassReference:Class = getDefinitionByName(className) as Class;
			var sprite:Sprite = new ClassReference() as Sprite;
			
			var size:Number = Constant.ENTITY_SIZE - offset;
			sprite.scaleX = size / sprite.width;
			sprite.scaleY = size / sprite.height;
			
			entity.setImage( rasterize(sprite) );  
		}
		
		override public function position():void
		{
			entity.position(offset);
		}
		
		override public function playEffect():void
		{
			entity.appear();
		}
		
		private function rasterize(sprite:Sprite):DisplayObject
		{
			var backdown:Rectangle = sprite.getBounds( fakeSprite ); //The fake display object that defines the coordinate system to use.
			var bmpMatrix:Matrix = sprite.transform.matrix;
			bmpMatrix.translate( -backdown.x, -backdown.y );
			
			var bmpData:BitmapData = new BitmapData( sprite.width, sprite.height, true, 0);
			//The draw method copies the vector data to the BitmapData instance
			bmpData.draw(sprite, bmpMatrix);
			
			//Render Bitmap instance
			return new Bitmap(bmpData);
		}
				
	}
}